<template>
        <el-upload
                ref="uploadRef"
                class="upload-demo"
                :action = actionUrl
                :auto-upload="false"
                list-type="picture"
                :before-upload="beforeUpload"
                :on-success = onSuccess
                :on-error = onError
        >
                <template #trigger>
                        <el-button type="primary">选择文件</el-button>
                </template>

                <el-button class="ml-3" type="success" @click="submitUpload">
                        上传
                </el-button>

                <template #tip>
                        <div class="el-upload__tip">
                                必须是 JPG或PNG 格式，文件大小不能大于2MB!
                        </div>
                </template>
        </el-upload>
</template>

<script setup>
    import {ref,reactive,onMounted} from 'vue'
    import { ElMessage } from 'element-plus'
    let uploadRef = ref(null)
    let props = defineProps(['type'])
    let actionUrl = ref("")
    const  emits = defineEmits(['close','uploadSuccess'])

    onMounted(function () {
            actionUrl.value = '/api/common/upload/' + props.type
            uploadRef.value.clearFiles()
    })

    const beforeUpload = (rawFile) => {
            console.log("文件格式："+rawFile.type)
            if (rawFile.type !== 'image/jpeg'
                    && rawFile.type !== 'image/png'
                    && rawFile.type !== 'image/gif'
                    && rawFile.type !== 'image/avif'
            ) {
                    ElMessage.error('必须是 JPG，PNG，gif，avif 格式!')
                    return false
            } else if (rawFile.size / 1024 / 1024 > 2) {
                    ElMessage.error('文件大小不能大于2MB!')
                    return false
            }
            return true
    }

    function submitUpload(){
            uploadRef.value.submit()
    }

    function onSuccess(response, uploadFile, uploadFiles){
            console.log(response.data)
            ElMessage.success('上传成功!')
            emits("uploadSuccess", response.data)
            uploadRef.value.clearFiles()
    }

    function onError(error, uploadFile, uploadFiles){
            console.log(error)
            ElMessage.success('上传失败-' + error)
    }

</script>

<style scoped>

</style>